import * as crypto from "crypto";
import { Application } from 'pinus';

export class Token {


    // Object.defineProperty(exports, "__esModule", { value: true });
    // exports.HTTP_KEY = exports.MAX_TABLE_USER = exports.TOKEN_USEFUL_TIME = exports.TOKEN_PWD = exports.IV_LENGTH = void 0;
    // exports.IV_LENGTH = 16;
    // exports.TOKEN_PWD = 'cP3hsLrfN0l7QOdO4ETgzqLYc6ly69jjbCQIHMJ4cxc=';
    // exports.TOKEN_USEFUL_TIME = 30000;
    // exports.MAX_TABLE_USER = 4;
    // exports.HTTP_KEY = 'f98b6dad17b70aac';


    public static create(uid: string): string {
        // let app: Application = new Application()
        let IV_LENGTH = 16
        let TOKEN_PWD = 'Aha5KisWztCLhtESUiXtnEiAY9oGzVs/x8LfGMchs2k='// app.get('secret') 

        const text = Date.now() + "|" + uid + "|" + Math.floor(Math.random() * 10000)
        let iv = crypto.randomBytes(IV_LENGTH);
        let cipher = crypto.createCipheriv('aes-256-ctr', Buffer.from(TOKEN_PWD, 'base64'), iv);
        let encrypted: Buffer = cipher.update(Buffer.from(text));
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return iv.toString('hex') + ':' + encrypted.toString('hex'); //xxxxx:xxxx   xcxc.xxx.xx
    }

    public static parse(token: string, key: string): { uid: string, timeKey: number } {
        let textParts = token.split(':');
        let iv = Buffer.from(textParts.shift(), 'hex');
        let encryptedText = Buffer.from(textParts.join(':'), 'hex');
        let decipher = crypto.createDecipheriv('aes-256-ctr', Buffer.from(key, 'base64'), iv);
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()])

        const result: string[] = decrypted.toString().split('|');
        if (result.length !== 3) {
            return null;
        }
        return { uid: result[1], timeKey: Number(result[0]) }
    }

    public static check(authInfo: { uid: string, timeKey: number }, useful: number) {
        if (!authInfo || !authInfo.timeKey || !authInfo.uid) {
            return false;
        }
        let nowTime = Date.now();
        return ((nowTime - authInfo.timeKey) < useful);
    }

}
